package cn.yunhe.servlet;

import cn.yunhe.entity.News;
import cn.yunhe.service.NewsService;
import cn.yunhe.util.JsonUtil;
import cn.yunhe.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/NewsJsonServlet")
public class NewsJsonServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String keyword = request.getParameter("keyword");
        int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));

        NewsService newsService = new NewsService();
        List<News> newsList = newsService.getNewsByPage(pageIndex, keyword);
        int newsCount = newsService.getNewsCount();  //总条数
        int totalPages = PageUtil.getTotalPages(newsCount);

        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("newsList", newsList);
        maps.put("pageIndex", pageIndex);
        maps.put("totalPages", totalPages);

        JsonUtil.getJson(response, maps);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
